package com.dev.manager.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dev.common.base.controller.BaseController;
import com.dev.common.util.MD5;
import com.dev.common.util.StringUtil;
import com.dev.facade.entity.SyUserInfo;
import com.dev.facade.service.SyUserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;

/**
 * @author Shiwen .Li
 * @version V1.3.1
 * @Description
 * @date 2016年7月14日 下午3:28:56
 */
@Controller
@RequestMapping("user")
public class SyUserInfoController extends BaseController {

    /**
     * 系统用户 业务实例
     */
    @Resource
    protected SyUserInfoService userService;

    /**
     * 转到用户列表页
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String list() {
        logger.info("用户列表页面");
        return "user/list";
    }

    /**
     * 检测当前用户是否存在
     *
     * @return
     */
    @RequestMapping("checkUserIsExist")
    @ResponseBody
    public HashMap<String, String> checkUserIsExist(SyUserInfo user) {
        HashMap<String, String> result = new HashMap<String, String>();

        ArrayList<SyUserInfo> users = userService.selectList(user);

        if (users != null && users.size() != 0) {
            result.put("status", "0");
            result.put("msg", "账号已被使用!");
        } else {
            result.put("status", "1");
            result.put("msg", "账号可以使用!");
        }
        return result;
    }

    /**
     * 添加用户信息
     *
     * @param user
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String register(SyUserInfo user, HttpServletResponse response,
                           HttpServletRequest request) throws IOException, ServletException {
        int result = 0;
        try {
            result = userService.addUser(user);
        } catch (Exception e) {
        }
        String msg = "";
        String path = "";
        if (result != 0) {
            msg = "注册成功,请到您的邮箱激活账号！！";
            path = "login";
        } else {
            msg = "注册失败！！";
            path = "register";
        }
        request.setAttribute("msg", msg);
        return path;
    }

    /**
     * 用户登录
     *
     * @param userinfo
     * @param request
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String userLogin(SyUserInfo userinfo, HttpServletRequest request)
            throws ServletException, IOException {
        String result="";

        Subject subject = SecurityUtils.getSubject();
        // 加密密码
        userinfo.setPassword(MD5.encryption(userinfo.getPassword()));
        logger.info("登录信息", userinfo.toString());
        // 登录令牌
        UsernamePasswordToken token = new UsernamePasswordToken(
                userinfo.getAccount(), userinfo.getPassword());
        try {
            subject.login(token);
            if (!subject.isRemembered()) {
                logger.info("记住登录信息");
                token.setRememberMe(true);
            }
            //保存登录者信息
            SyUserInfo user = new SyUserInfo();
            user.setAccount(userinfo.getAccount());
            List<SyUserInfo> users = userService.selectList(user);
            subject.getSession().setAttribute("user", users.get(0));

            result= "redirect:/index";
        } catch (UnknownAccountException uae) {
            logger.info("username wasn't in the system.");
            result="login";
        } catch (IncorrectCredentialsException ice) {
            logger.info("password didn't match.");
            result="login";
        } catch (LockedAccountException lae) {
            logger.info("account for that username is locked - can't login.");
            request.setAttribute("msg", "账号已锁定，请稍后再登录！");
            result="login";
        } catch (AuthenticationException ae) {
            logger.info("登录失败", ae);
            request.setAttribute("user", userinfo);
            request.setAttribute("msg", "用户名或密码错误！");
            result="login";
        }
        return result;
    }

    @RequestMapping(value = "getinfo/{account}", method = RequestMethod.GET)
    public void getInfo(@PathVariable(value = "account") String account,
                        HttpServletResponse response, HttpServletRequest request)
            throws ServletException, IOException {
        logger.info("账号:" + account);
        SyUserInfo user = new SyUserInfo();
        user.setAccount(account);
        List<SyUserInfo> userList = userService.selectList(user);
        if (userList.size() == 0) {
            throw new RuntimeException("错误");
        }
        logger.info("获取的用户信息", userList.get(0));
        request.setAttribute("user", userList.get(0));
        request.getRequestDispatcher("/temp/profile.jsp").forward(request,
                response);
    }

    /**
     * 修改个人信息
     *
     * @param userinfo
     * @param file     头像文件
     * @param response
     * @param request
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void updateProfile(
            SyUserInfo userinfo,
            @RequestParam(value = "head", required = false) CommonsMultipartFile file,
            HttpServletResponse response, HttpServletRequest request,
            HttpSession session) throws ServletException, IOException {
        String path = "/index.jsp";// 跳转页面
        String msg = "";// 返回消息
        logger.info("文件", file.getSize());
        if (file.getSize() != 0) {
            // 上传保存路径
            String realPath = request.getServletContext().getRealPath(
                    "/static/file/img");
            // 新名字
            String newName = UUID.randomUUID().toString().replace("-", "")
                    + StringUtil.getSubString(file.getOriginalFilename(), ".");
            try {
                file.getFileItem().write(new File(realPath, newName));
                userinfo.setHeadPicture(newName);
            } catch (Exception e) {
            }
        }

        logger.info("修改用户信息", userinfo);
        if (userService.update(userinfo) == 1) {
            msg = "修改成功!!";
        } else {
            msg = "修改成功!!";
            path = "/temp/profile.jsp";
        }

        request.setAttribute("msg", msg);
        request.getRequestDispatcher(path).forward(request, response);

    }

    /**
     * 导出用户信息 excel 表格
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public void exportExcel(HttpServletResponse response,
                            HttpServletRequest request) throws IOException {
        logger.info("导出用户信息");
        userService.exportExcel(response);
    }

    /**
     * @param response
     * @param user     筛选信息
     * @throws IOException
     */
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public void data(HttpServletResponse response, @RequestBody SyUserInfo user)
            throws IOException {
        Page<SyUserInfo> page = userService.getListByPage(user);
        this.bootstrapDataTable(response, page);
    }

    @RequestMapping("active")
    public String active(HttpServletRequest request, SyUserInfo userinfo) {
        List<SyUserInfo> userList = userService.selectList(userinfo);
        if (userList.size() != 0 && !userList.isEmpty()) {
            userinfo = userList.get(0);
            userinfo.setStatus(1);
            userService.update(userinfo);
        }
        request.setAttribute("user", userinfo);
        request.setAttribute("msg", "恭喜" + userinfo.getAccount() + "用户,您 的账号激活成功，请登录！");
        return "login";
    }

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping(value = {"/tologin"})
    public ModelAndView toLogin() {
        return new ModelAndView("login");
    }

    /**
     * 转到注册页面
     *
     * @return
     */
    @RequestMapping(value = {"/toregister"})
    public ModelAndView toRegister() {
        return new ModelAndView("register");
    }

    /**
     * 转到忘记密码页面
     */
    @RequestMapping(value = {"/forget"})
    public ModelAndView toForget() {
        return new ModelAndView("user/forget_password");
    }


    /**
     * 转到个人资料页面
     */
    @RequestMapping(value = {"/profile"}, method = RequestMethod.GET)
    public String profile() {
        return "user/profile";
    }
}
